package com.yhgm.utils;

import com.yhgm.constant.Constant;
import com.yhgm.mapper.SystemLogDao;
import com.yhgm.model.entity.SystemLog;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author moon
 * @description 全局异常拦截
 * @date 2022/6/3
 */
@ControllerAdvice
public class GlobalExceptionAdvice {
    @Resource
    private SystemLogDao systemLogDao;
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R exceptionHandler(Exception e) {
        Map<String, Object> map = new HashMap<>();
        Integer code = Constant.ERROR_CODE;
        SystemLog systemLog = new SystemLog();
        systemLog.setErrorMsg(e.getClass().getName() + ":" + e.getMessage());
        systemLog.setEventTime(new Date(System.currentTimeMillis()));
        map.put("error", e.getMessage());
        map.put("status", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        map.put("exception", e.getClass().getName());
        map.put("timestamp", systemLog.getEventTime());
        HttpServletRequest request = ((ServletRequestAttributes) (Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) (Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))).getResponse();
        map.put("path", request.getRequestURI());
        systemLog.setRequestUrl(request.getRequestURI());
        Objects.requireNonNull(response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        String msg="error";
        if (e.getClass().getName().startsWith("cn.dev33.satoken")) {
            code = Constant.TOKEN_ERROR_CODE;
            msg="登录过期";
        }
        //systemLogDao.addOne(systemLog);
        e.printStackTrace();
        return new R(code, map, msg);
    }
}
